/**
 *
 */
package com.hz.dao.impl;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

import com.hz.dao.UserDao;
import com.hz.model.User;
import com.hz.services.UserServices;
import com.hz.utils.JdbcUtil;

/**
 * @author Administrator
 * @date 2018年6月20日 上午10:22:42
 * 
 */
public class UserDaoImpl implements UserDao {

	@Override
	public void add(User user) {
		String sql = "insert into user"
				+ "(name,password) values('" + user.getName() 
				+"' ,'" + user.getPassword() +"')";
		System.out.println("add：" + sql);
		try {
			JdbcUtil.excute(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	@Override
	public void mod(User user) {
		String sql = "update user set name = '" +user.getName() +"',"
				+ " password='" + user.getPassword() +"'"
						+ " where id= " + user.getId();
		System.out.println("mod：" + sql);
		try {
			JdbcUtil.excute(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	@Override
	public void del(int id) {
		String sql = "delete from user where id = " + id;
		System.out.println("del：" + sql);
		try {
			JdbcUtil.excute(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	@Override
	public List<User> query(User user) {
		String sql = "select id, name ,password,cre_user as creUser from user where 1=1 ";
		if(user.getName() != null && user.getName() != "") {
			sql += " and name = '" + user.getName()+"'";
		}
		System.out.println("query：" + sql);
		List<Map> lists = new ArrayList<>();
		try {
			//执行查询语句，得到查询结果
			lists = JdbcUtil.excuteQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		List<User> results = new ArrayList<>();
		for(int i = 0 ; i< lists.size(); i++) {
			Map temMap = lists.get(i);
			User temUser = new User();
			try {
				BeanUtils.populate(temUser, temMap);
			} catch (IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
			}
			results.add(temUser);
		}
		
		return results;
	}

	@Override
	public int login(User user) {
		String sql = "select count(1) as count from user where "
				+ "name='" + user.getName() +"' and password='" + user.getPassword()+"'" ; 
		List<Map> lists = new ArrayList<>();
		System.out.println("login：" + sql);
		try {
			 lists = JdbcUtil.excuteQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		int count = Integer.parseInt(lists.get(0).get("count").toString());
		return count;
	}

}
